package com.ds.common.route.config;

import com.google.common.collect.Lists;
import com.ds.common.route.agent.Agent;
import lombok.extern.slf4j.Slf4j;
import org.mvel2.MVEL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 配置中心服务
 */
@Service
@Slf4j
public class ConfigCenterService {


    AgentConfigService agentConfigService;
    ClusterConfigService clusterConfigService;

    //构造函数
    @Autowired
    public ConfigCenterService(AgentConfigService agentConfigService, ClusterConfigService clusterConfigService) {
        this.agentConfigService = agentConfigService;
        this.clusterConfigService = clusterConfigService;
    }

    public ClusterConfig getClusterConfig(String clusterName) {
        return Optional.ofNullable(clusterConfigService.getValue()).map(x -> x.getClusterConfig(clusterName)).orElse(null);
    }

    public AgentConfig getAgentConfig(Integer agentId) {
        return Optional.ofNullable(agentConfigService.getValue()).map(x -> x.agentConfigMap.get(agentId)).orElse(null);
    }

    public ClusterConfig match(Agent agent) {

        if (agent == null || clusterConfigService.getValue() == null) {
            return ClusterConfig.DEFAULT;
        }
        List<ClusterConfig> clusters = Lists.newArrayList();
        for (ClusterConfig clusterConfig : clusterConfigService.getValue().getClusterConfigList()) {
            Map<String, Object> context = new HashMap<>();
            context.put("agentId", agent.getAgentId());
            context.put("agentGropId", agent.getAgentGroupId());
            try {
                Object result = MVEL.executeExpression(clusterConfig.getConditionExpression(), context);
                if (result != null && Boolean.parseBoolean(result.toString())) {
                    clusters.add(clusterConfig);
                }
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
            }
        }
        if (!CollectionUtils.isEmpty(clusters)) {
            return clusters.stream().max(Comparator.comparing(ClusterConfig::getPriority)).get();
        }
        return ClusterConfig.DEFAULT;
    }


}
